using Demo.Models;
using Demo.Repository;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System.Collections.Generic;
using Demo.RequestParam;

namespace Demo.Controllers
{
    public class ProductController:Controller
    {
        public IActionResult Index()
        {
            var CateRep = new EfRepository<Category>();
            var cate = CateRep.table.FirstOrDefault();
            if (cate == null)
            {
                CateRep.Insert(new Category{
                    CategoryName = "清华",
                });
            }
            var ProRep = new EfRepository<Product>();
            IList<Product> pro = ProRep.table.Where(x=>x.IsDeleted == false).ToList();
           
            return View(pro);
        }
        public IActionResult Query(ProductQueryParam request)
        {
            var proRep = new EfRepository<Product>();
            var pro = proRep.table.Where(x=>x.IsDeleted == false && x.ProductName.Contains(request.keywork)).ToList();
            return Json(pro);
        }
        public IActionResult CreateOnEdit(int Id)
        {
            if(Id == 0)
            {
                return View();
            }else
            {
                var proRep = new EfRepository<Product>();
                var pro = proRep.table.Where(x=>x.Id == Id).FirstOrDefault();
                return View(pro);
            }
        }
        public IActionResult Save(Productparam request)
        {
            var proRep = new EfRepository<Product>();
            if (request.Id == 0)
            {
                proRep.Insert(new Product{
                    ProductName = request.ProductName,
                    Supplier = request.Supplier,
                    Price = request.Price,
                    Stock = request.Stock,
                    Remarks = request.Remarks,
                    CategoryId = 1,
                });
            }else
            {
                var pro = proRep.table.Where(x=>x.Id == request.Id).FirstOrDefault();
                   pro.ProductName = request.ProductName;
                    pro.Supplier = request.Supplier;
                    pro.Price = request.Price;
                    pro.Stock = request.Stock;
                    pro.Remarks = request.Remarks;
                    proRep.Update(pro);
            }
            return Ok();
        }
        public IActionResult Delete(int Id)
        {
            var proRep = new EfRepository<Product>();
            proRep.Delete(Id);
            return RedirectToAction("Index");
        }
    }
}